﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace RenderServer
{
    class BroadcastServer
    {
        private UdpClient client;
        private IPEndPoint endpoint;
        private Thread broadcaster;

        private bool started;
        private bool broadcast;
        private bool stop;

        public BroadcastServer(int port)
        {
            endpoint = new IPEndPoint(IPAddress.Broadcast, port);
            client = new UdpClient();
            client.AllowNatTraversal(true);

            broadcaster = new Thread(cast);

            broadcast = false;
            started = false;
            stop = false;
        }

        public void Start()
        {
            broadcast = true;
            started = true;
            stop = false;
            broadcaster.Start();

            Console.WriteLine("Broadcasting on port {0}", endpoint.Port);
        }

        public void Stop()
        {
            if (!started) { throw new InvalidOperationException("The broadcaster must have been started to be stopped."); }
            stop = true;
            broadcast = false;
        }

        public void Pause()
        {
            if (!started) { throw new InvalidOperationException("The broadcaster must have been started to be paused."); }
            stop = false;
            broadcast = false;
        }

        public void Resume()
        {
            if (!started) { throw new InvalidOperationException("The broadcaster must have been started to be resumed."); }
            stop = false;
            broadcast = true;
        }

        private void cast()
        {
            byte[] message = Encoding.ASCII.GetBytes("TracedReality Broadcast");
            while (!stop)
            {
                if (broadcast)
                {
                    client.Send(message, message.Length, endpoint);
                }

                Thread.Sleep(1000);
            }
        }
    }
}
